package com.ipan.builder.db.comment;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ipan.builder.db.DatabaseOp;
import com.ipan.builder.entity.JpaEntityCfg;

/**
 * 注释操作基类（提供创建工厂）
 * 
 * @author iPan
 * @version 2013-12-7
 */
public abstract class BaseCommentOp implements CommentOp {

	public static final String SQL_COLUMN = "column";
	public static final String SQL_TABLE = "table";
	public static final String SQL_COMMENT = "comment";
	public static final String SQL_TYPE = "type";
	public static final String SQL_AUTO = "auto";
	
	protected DatabaseOp databaseOp;
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	public BaseCommentOp(DatabaseOp databaseOp) {
		this.databaseOp = databaseOp;
	}

	public void updateAll(JpaEntityCfg entityCfg) {
		updateTableComment(entityCfg);
		updateColumnComment(entityCfg);
	}

	/**
	 * 根据不同数据库方言获取对应的处理器
	 */
	public static CommentOp createCommentOpByDialect(Dialect dialect, DatabaseOp databaseOp) {
		CommentOp op = null;
		if (dialect != null) {
			if (dialect instanceof Oracle8iDialect) {
				op = new OracleCommentOp(databaseOp);
			} else if (dialect instanceof MySQLDialect) {
				op = new MysqlCommentOp(databaseOp);
			} else if (dialect instanceof SQLServerDialect) {
				op = new SqlServerCommentOp(databaseOp);
			}
		}
		return op;
	}

	/**
	 * 根据不同数据库方言名称获取对应的处理器
	 */
	public static CommentOp createCommentOpByDialectName(String dialectName, DatabaseOp databaseOp) {
		CommentOp op = null;
		if (dialectName.toLowerCase().contains("oracle")) {
			op = new OracleCommentOp(databaseOp);
		} else if (dialectName.toLowerCase().contains("mysql")) {
			op = new MysqlCommentOp(databaseOp);
		} else if (dialectName.toLowerCase().contains("sqlserver")) {
			op = new SqlServerCommentOp(databaseOp);
		}
		return op;
	}

	public abstract void updateTableComment(JpaEntityCfg entityCfg);

	public abstract void updateColumnComment(JpaEntityCfg entityCfg);

	/**
	 * 获取配置的SchemaName
	 */
	protected String getSchemaName() {
		return databaseOp.getSchemaName();
	}
	
	/**
	 * 获取配置的CatalogName
	 */
	protected String getCatalogName() {
		return databaseOp.getCatalogName();
	}
	
	protected String fillSql(String sql, String name, String value) {
		String expr = "\\{\\s*" + name + "\\s*\\}";
		return sql.replaceAll(expr, value);
	}
	
}
